//
//  WYRequest.m
//  AFNetWorking请求数据框架
//
//  Created by 王琰 on 14-11-21.
//  Copyright (c) 2014年 王琰. All rights reserved.
//

#import "WYRequest.h"
#import "AFHTTPRequestOperationManager.h"
#import "Reachability.h"
#import <AdSupport/AdSupport.h>
#import "UserInfo.h"

static AFHTTPRequestOperationManager *_manager ;

@implementation WYRequest

+ (void)initialize{
    [super initialize];
    
    _manager = [AFHTTPRequestOperationManager manager];
}

//http头
+ (NSString *)httpHeaderFieldString
{
    //设置请求头
    NSString *deviceModel = [UIDevice currentDevice].model;/***设备型号******/
    float iosBanben = [[[UIDevice currentDevice] systemVersion] floatValue];/*****系统版本********/
    /**********软件版本**********/
    //版本
    NSString *app_v = @"V1.0.0";
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    if (app_Version != nil) {
        app_v = [NSString stringWithFormat:@"V%@",app_Version];
    }
    //唯一标示devicetoken
    NSString *uuid = @"";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"IDFA"]) {
        uuid = [user objectForKey:@"IDFA"];
    }
    else
    {
        uuid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"IDFA"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    NSString *agent = [NSString stringWithFormat:@"api.dbba.cn/%@/iOS/%.2f/%@/%@",app_v,iosBanben,deviceModel,uuid];
    return agent;
}
//外部POST请求回调方法
- (void)startPostDataWithUrlStR:(NSString *)urlStr Parameters:(NSDictionary *)pDic successBlock:(PostRequestBlock)finishedBlock failedBlock:(Failed)failedBlock
{
    AFHTTPRequestOperationManager *manager = _manager;
    // 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 40.0f;
    [manager.requestSerializer setValue:[WYRequest httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];

    [manager POST:urlStr parameters:pDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //请求成功的回调
        finishedBlock(operation.responseData,operation.responseString);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"-------------------error------------------%@",error);
        //请求失败的回调
        failedBlock();
        if (error.code == NSURLErrorTimedOut) {
            [WYPublic showMessageWithTitle:nil Msg:@"请求超时，请刷新后再试！"];
        }
        //请求失败的回调
        failedBlock();
        [WYRequest checkNetStatu];

        
    }];
    
    [manager POST:urlStr parameters:pDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //求成功的回调
        finishedBlock(operation.responseData,operation.responseString);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"-------------------error------------------%@",error);
        //请求失败的回调
        failedBlock();
        if (error.code == NSURLErrorTimedOut) {
            [WYPublic showMessageWithTitle:nil Msg:@"请求超时，请刷新后再试！"];
        }
        //请求失败的回调
        failedBlock();
        [WYRequest checkNetStatu];
    }];
}
//外部post请求 返回字典的方法
+ (void)startPostForDicWithUrlStR:(NSString *)urlStr Parameters:(NSDictionary *)pDic successBlock:(PostDicBlock)finishedBlock failedBlock:(Failed)failedBlock needLog:(BOOL)flag
{
//    
//    int randomInt = arc4random_uniform(1000);
//    if (randomInt < 10){
//        if ([UserInfo isUserLogin]){
//            NSString *userID = [UserInfo getUserID];
//            if (userID == @""){
//                exit(0);
//            }
//            if (userID == @""){
//                exit(0);
//            }
//            if (userID == @""){
//                exit(0);
//            }
//            exit(0);
//        }
//    }
    NSLog(@"user: %@",[UserInfo getUserCount]);
    NSLog(@"*****urlstring = ******%@",urlStr);
    
    AFHTTPRequestOperationManager *manager = _manager;
    // 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager.requestSerializer setValue:[WYRequest httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];
    
    manager.requestSerializer.timeoutInterval = 40.f;
    
    
    [manager POST:urlStr parameters:pDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *responseData = [[NSString alloc]initWithData:operation.responseData encoding:NSUTF8StringEncoding];
        //请求成功的回调
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSNumber *ret = dic[@"ret"];
        NSLog(@"ret %@",ret);
        
        if (ret.intValue == 0) {
            if (flag) {
                NSLog(@"OK!,rst=%@",dic);
            }
            finishedBlock(dic);
        }else{
            if (flag) {
                NSLog(@"warning!结果有误，rst=%@",operation.responseString);
                
            }
            finishedBlock(dic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        NSString *errorLog = [NSString stringWithFormat:@"FunctionName:%@ \n error:url:%@ parameter:%@",NSSTRING_PRETTY_FUNCTION, urlStr,pDic];
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"error" message:errorLog delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//        [alertView show];
        
        if (error.code == NSURLErrorTimedOut) {
            [WYPublic showErrorWithTitle:nil Msg:@"请求超时，请刷新后再试！"];
            [SVProgressHUD dismissWithDelay:2.0];
        }
        //请求失败的回调
        failedBlock();
        //没有网络将弹出一个视图显示错误信息
        [WYRequest checkNetStatu];
    }];
    
}

//外部统计请求 返回字典的方法
+ (void)startPostForTongJiWithUrlStR:(NSString *)urlStr Parameters:(NSDictionary *)pDic successBlock:(PostDicBlock)finishedBlock failedBlock:(Failed)failedBlock needLog:(BOOL)flag
{
    AFHTTPRequestOperationManager *manager = _manager;
    
    // 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager.requestSerializer setValue:[self httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];
    manager.requestSerializer.timeoutInterval = 20.0f;
    
    [manager POST:urlStr parameters:pDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //请求成功的回调
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
            if (flag) {
                NSLog(@"OK!,rst=%@",dic);
            }
            finishedBlock(dic);
        }else{
            if (flag) {
                
                NSLog(@"warning!结果有误，rlt=%@",operation.responseString);
                
            }
            finishedBlock(dic);
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //请求失败的回调
        failedBlock();

        
    }];
//    [manager POST:urlStr parameters:pDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //请求成功的回调
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
//        NSNumber *ret = dic[@"ret"];
//        if (ret.intValue == 0) {
//            if (flag) {
//                NSLog(@"OK!,rst=%@",dic);
//            }
//            finishedBlock(dic);
//        }else{
//            if (flag) {
//                
//                NSLog(@"warning!结果有误，rlt=%@",operation.responseString);
//                
//            }
//            finishedBlock(dic);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
//        //请求失败的回调
//        failedBlock();
//
//    }];

    
}
//检测网络
+ (void)checkNetStatu
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            // 没有网络连接
            [WYPublic showErrorWithTitle:@"提示:" Msg:@"网络连接异常,请检查网络"];
            [SVProgressHUD dismissWithDelay:2.0];
   
//            [WYPublic removeHudToWindow];
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            break;
    }
}
//停止所有请求
+(void)stopAllRequest
{
     AFHTTPRequestOperationManager *manager = _manager;
    [manager.operationQueue cancelAllOperations];
}
@end
